import { _decorator, Button, Component, EditBox, find, instantiate, log, Node, Prefab } from 'cc';
import { EzGameNet } from './api/base/EzGameNet';
import { SyncApi } from './api/SyncApi';
import { JSB } from 'cc/env';
import { Player } from './prefab/Player';
import { SyncPushMsgEnum } from './api/SyncPushMsgEnum';
const { ccclass, property } = _decorator;

@ccclass('Game')
export class Game extends Component {

    game: Node;
    ui: Node;
    uiName:EditBox;
    connect:Node;
    net:EzGameNet

    @property({type:Prefab})
    playerPrefab:Prefab

    players:Map<number,Player> = new Map()

    start() {
        this.game = this.node.getChildByName("game");
        this.ui = this.node.getChildByName("ui")
        this.uiName = this.node.getChildByPath("ui/name").getComponent(EditBox)
        this.connect = this.node.getChildByPath("ui/connect");
        this.connect.on(Button.EventType.CLICK,this.connectServer,this)

        //监听服务求推送消息
        SyncPushMsgEnum.addListener(SyncPushMsgEnum.Move,(data)=>{
          
        })
    }
    connectServer(){
        if(!this.uiName.string){
            console.log("未设置id")
            return
        }
        if(this.net && this.net.status==2){//已连接状态
            this.net.close()
        }
        //TODO 单体服的时候按服务名生成，如果是集群模式呢？
        this.net = EzGameNet.create("ws://localhost:13000/ws", {
            log:true,
            onNetOpen:(e)=>{
              console.log("全局日志：连接已连接！",e);
              this.enterMap()
            },
            onNetError:(e)=>{
              console.log("全局日志：连接出错！",e);
            },
            onNetClose:(e)=>{
              console.log("全局日志：连接已关闭！",e);
            }
          })
        this.net.connect()
    }
    enterMap() {
        SyncApi.enterMap()
        .reqParam(param=>{
          param.id = Number(this.uiName.string) as any
          param.color = ""
          return param
        }).onResp(req=>{
          if(req.respCode!=0){
              return
          }
          let playerData = req.respData
          let localPlayer = instantiate(this.playerPrefab)
          let player = localPlayer.getComponent(Player)
          player.init(playerData,true)
          this.players.set(playerData.id as unknown as number,player)
          this.game.addChild(localPlayer)
        }).sendAsync()
    }

    
}


